package leetcode101.ch3;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

//LC 159
public class LengthOfLongestSubstringTwoDistinct {
    public int lengthOfLongestSubstringTwoDistinct(String s) {
        if (s.length() <= 2) {
            return s.length();
        }
        Map<Character, Integer> map = new HashMap<>();

        int length = 0;
        for (int l = 0, r = 0 ; r < s.length(); r++) {
            map.put(s.charAt(r), r);
            if (map.size() > 2) {
                int leftIdx = Collections.min(map.values());
                map.remove(s.charAt(leftIdx));
                l = leftIdx + 1;
            }else {
                length = Math.max(r - l + 1, length);
            }
            System.out.println(length);
        }
        return length;
    }

    public static void main(String[] args) {
        new LengthOfLongestSubstringTwoDistinct().lengthOfLongestSubstringTwoDistinct("abcd");
    }
}
